import { Button, Form, Input, Modal, Table } from 'antd'
import styles from './index.module.scss'
import { useEffect, useState } from 'react'
import { profileAPI } from '@/apis'
import { genMaxId } from './utils'

export default () => {
  const [loading, setLoading] = useState(false)
  const [data, setData] = useState(() => {
    return {
      list: [],
      visible: false,
      formData: {
        id: null,
        name: null, // 企业画像等级名称
        minScore: null, // 总得分
        maxScore: null, // 总得分
      },
    }
  })

  const loadList = async () => {
    setLoading(true)
    try {
      const list = await profileAPI.getEnterpriseProfileLevel('/enterprise/profile/level')
      setData({
        ...data,
        list: list,
      })
    } catch (error) {
      console.log('error', error)
    }
    setLoading(false)
  }

  useEffect(() => {
    loadList()
  }, [])

  const openDetailDialog = (row) => {
    let formData = {
      id: null,
      name: null, // 企业画像等级名称
      minScore: null, // 总得分
      maxScore: null, // 总得分
    }
    if (row) {
      formData = {
        id: row.id,
        name: row.name, // 企业画像等级名称
        minScore: row.minScore, // 总得分
        maxScore: row.maxScore, // 总得分
      }
    }
    form.setFieldsValue(formData)
    setData({
      ...data,
      visible: true,
      formData: formData,
    })
  }

  const saveProfileLevel = async (list) => {
    console.log('save list', list)
    await profileAPI.saveEnterpriseProfileLevel('/enterprise/profile/level', list)
  }

  const openDelDialog = (row) => {
    Modal.confirm({
      title: '删除',
      content: '确定删除该条数据吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        const list = JSON.parse(JSON.stringify(data.list))
        const index = list.findIndex((item) => item.id === row.id)
        if (index !== -1) {
          list.splice(index, 1)
        }
        await saveProfileLevel(list)
        setData({ ...data, list })
      },
    })
  }

  const columns = [
    { title: 'id', width: '50px', dataIndex: 'id', key: 'id' },
    { title: '企业画像等级名称', dataIndex: 'name', key: 'name' },
    {
      title: '总得分',
      key: 'score',
      render: (text: any, record: any) => {
        const arr = []
        !isNaN(parseInt(record.minScore)) && arr.push(record.minScore)
        !isNaN(parseInt(record.maxScore)) && arr.push(record.maxScore)
        return arr.join('-') + '分'
      },
    },
    {
      title: '操作',
      width: '160px',
      key: 'name',
      render: (_, record) => (
        <>
          <Button size="small" color="default" type="link" onClick={() => openDetailDialog(record)}>
            编辑
          </Button>
          <Button size="small" color="default" type="link" onClick={() => openDelDialog(record)}>
            删除
          </Button>
        </>
      ),
    },
  ]

  const handleChangeVisible = (visible) => {
    setData({
      ...data,
      visible,
    })
  }

  const [form] = Form.useForm()
  const handleSubmit = async () => {
    await form.validateFields()
    const formData = form.getFieldsValue()
    const list = JSON.parse(JSON.stringify(data.list))
    if (data.formData.id) {
      const row = list.find((item) => item.id === data.formData.id)
      row.name = formData.name
      row.minScore = formData.minScore
      row.maxScore = formData.maxScore
    } else {
      list.push({
        id: genMaxId(data.list),
        name: formData.name,
        minScore: formData.minScore,
        maxScore: formData.maxScore,
      })
    }
    await saveProfileLevel(list)
    setData({
      ...data,
      visible: false,
      list: list,
    })
  }

  return (
    <div className={styles.page}>
      <div className={styles.header}>
        <div className={styles.title}>园区画像等级</div>
        <div className={styles.search}>
          <Button
            type="primary"
            onClick={() => {
              openDetailDialog(null)
            }}
          >
            添加
          </Button>
        </div>
      </div>
      <div className={styles.table}>
        <Table loading={loading} columns={columns} dataSource={data.list} pagination={false} rowKey="id" />
      </div>
      <Modal
        title={`园区画像评估规则内容-${data.formData.id ? '编辑' : '添加'}`}
        open={data.visible}
        onCancel={() => handleChangeVisible(false)}
        onOk={() => handleSubmit()}
        okText="保存"
        cancelText="取消"
        footer={(_, { OkBtn, CancelBtn }) => (
          <>
            <CancelBtn />
            <OkBtn />
          </>
        )}
      >
        <Form form={form} labelCol={{ span: 9 }} style={{ maxWidth: 750, padding: '10px 10px' }} labelAlign="right">
          <Form.Item
            label="规则企业画像等级名称"
            name="name"
            rules={[{ required: true, message: '请输入规则企业画像等级名称' }]}
          >
            <Input style={{ width: 300 }} placeholder="请输入规则企业画像等级名称" />
          </Form.Item>
          <Form.Item label="总得分" required>
            <Form.Item
              name="minScore"
              noStyle
              rules={[
                () => ({
                  validator(fieldInfo, value) {
                    if (value) {
                      return Promise.resolve()
                    }
                    return Promise.reject(new Error('请填写得分'))
                  },
                }),
              ]}
            >
              <Input style={{ width: 110 }} min={0} max={100} type="number" placeholder="请填写数字"></Input>
            </Form.Item>
            <span style={{ margin: '0 10px' }}>至</span>
            <Form.Item
              name="maxScore"
              noStyle
              rules={[
                () => ({
                  validator(fieldInfo, value) {
                    if (value) {
                      return Promise.resolve()
                    }
                    return Promise.reject(new Error('请填写得分'))
                  },
                }),
              ]}
            >
              <Input style={{ width: 110 }} type="number" min={0} max={100} placeholder="请填写数字"></Input>
            </Form.Item>
            <span style={{ marginLeft: '10px' }}>分</span>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}
